﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using yncTech.BusinessObjects;
using System.Data;
using System.Collections;
using EntitySpaces.Interfaces;

public partial class Admin_SAPFin_SAPFin002d : AdminBasePage
{
    protected decimal? boxId;
    //protected string companyCode = string.Empty;
    //protected string companyName = string.Empty;
    //protected string year = string.Empty;
    //protected string monthStart = string.Empty;
    //protected string monthEnd = string.Empty;
    //protected string indexStart = string.Empty;
    //protected string indexEnd = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["BoxId"] != null)
        {
            boxId = decimal.Parse(Request.QueryString["BoxId"]);
            FinBox finBox = new FinBox();
            finBox.LoadByPrimaryKey(boxId.Value);
            drpCompany.SelectedValue = finBox.CompanyName + "(" + finBox.CompanyCode + ")";
            drpCompany.Enabled = false;

            drpKeyType.SelectedValue = finBox.IndexType.Value.ToString();
            drpKeyType.Enabled = false;

            txtKeyStart.Text = finBox.IndexStart;
            if (!string.IsNullOrEmpty(txtKeyStart.Text))
            { txtKeyStart.ReadOnly = true;

            txtKeyStart.ForeColor = System.Drawing.Color.Gray;
            }

            txtKeyEnd.Text = finBox.IndexEnd;
            if (!string.IsNullOrEmpty(txtKeyEnd.Text))
            { txtKeyEnd.ReadOnly = true; 
                txtKeyEnd.ForeColor = System.Drawing.Color.Gray; }

            txtPostingStartDate.Text = finBox.BoxYear.Value.ToString() + "-" + (finBox.BoxMonth.Value + 100).ToString().Substring(1, 2) + "-01";
            txtPostingStartDate.ReadOnly = true;
            if (finBox.BoxMonthEnd.HasValue)
            {
                txtPostingEndDate.Text = finBox.BoxYear.Value.ToString() + "-" + (finBox.BoxMonthEnd.Value + 100).ToString().Substring(1, 2) + "-01";
                txtPostingEndDate.ReadOnly = true;
            }
        }
        if (!IsPostBack)
        {
            if (Session["sd"] != null)
            {
                txtStartDate.Value = Session["sd"].ToString();
            }
            if (Session["ed"] != null)
            {
                txtEndate.Value = Session["ed"].ToString();
            }
            if (Session["drpDocType"] != null)
            {
                drpDocType.SelectedValue = Session["drpDocType"].ToString();
            }
            if (Session["txtKey"] != null)
            { txtKey.Text = Session["txtKey"].ToString(); }

            if (Session["drpFunctionDept"] != null)
            {
                drpFunctionDept.SelectedValue = Session["drpFunctionDept"].ToString();
            }
            if (Session["txtUserName"] != null)
            { txtUserName.Text = Session["txtUserName"].ToString(); }
            if (Session["txtDocumentsType"] != null)
            { txtDocumentsType.Text = Session["txtDocumentsType"].ToString(); }
            if (Session["txtReferenceTransact"] != null)
            { txtReferenceTransact.Text = Session["txtReferenceTransact"].ToString(); }
            if (Session["txtDocumentSystem"] != null)
            { txtDocumentSystem.Text = Session["txtDocumentSystem"].ToString(); }
            if (Session["txtLogicalSystem"] != null)
            { txtLogicalSystem.Text = Session["txtLogicalSystem"].ToString(); }
            if (Session["txtKeyMulti"] != null)
            { txtKeyMulti.Text = Session["txtKeyMulti"].ToString(); }
            if (Session["drpKeyType"] != null)
            {
                drpKeyType.SelectedValue = Session["drpKeyType"].ToString();
            }
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Session["drpDocType"] = drpDocType.SelectedValue;
        Session["txtKey"] = txtKey.Text.Trim();
        Session["drpFunctionDept"] = drpFunctionDept.SelectedValue;
        Session["sd"] = txtStartDate.Value;
        Session["ed"] = txtEndate.Value;
        Session["txtUserName"] = txtUserName.Text.Trim();
        Session["txtDocumentsType"] = txtDocumentsType.Text.Trim();
        Session["txtReferenceTransact"] = txtReferenceTransact.Text.Trim();
        Session["txtDocumentSystem"] = txtDocumentSystem.Text.Trim();
        Session["txtLogicalSystem"] = txtLogicalSystem.Text.Trim();
        Session["drpKeyType"] = drpKeyType.SelectedValue;
        Session["txtKeyMulti"] = txtKeyMulti.Text.Trim();
    }

    protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
    {
        FinReceiptQuery q1 = new FinReceiptQuery("q1");


        TSCodeTableQuery q2 = new TSCodeTableQuery("q2");
        TSCodeTableQuery q3 = new TSCodeTableQuery("q3");
        TSCodeTableQuery q4 = new TSCodeTableQuery("q4");
        TSCodeTableQuery q6 = new TSCodeTableQuery("q6");
        BFThirdUnitQuery q5 = new BFThirdUnitQuery("q5");
        BFCompanyDicQuery q7 = new BFCompanyDicQuery("q7");
        VReceiptExtInfoQuery q8 = new VReceiptExtInfoQuery("q8");

        TSCodeTableQuery q9 = new TSCodeTableQuery("q9");



        q1.LeftJoin(q9).On(q1.VoucherDescription == q9.Code);

        q1.LeftJoin(q2).On(q1.FunctionDept == q2.Code);
        q1.LeftJoin(q3).On(q1.StorageStatus == q3.Code);
        q1.LeftJoin(q4).On(q1.VoucherDescription == q4.Code);
        q1.LeftJoin(q5).On(q1.StorageLocation == q5.ThirdUnitID);
        q1.LeftJoin(q6).On(q1.Division == q6.Code);
        q1.LeftJoin(q7).On(q1.CompanyCode == q7.CompanyCode);
        q1.LeftJoin(q8).On(q1.ReceiptID == q8.ReceiptID);


        q1.SelectAll().Select(q2.Value1.As("FunctionDeptStr"), q3.Value1.As("StorageStatusStr"), q4.Value1.As("VoucherDescriptionName"), q5.Name.As("StorageLocationStr"), q6.Value1.As("DivisionStr"), q7.CompanyName, q7.CompanyCode, q8.SupplierBoxNo, q8.BoxNo, q9.Value1.As("DocDesc"));

        ArrayList args = new ArrayList();
        ArrayList argsOr = new ArrayList();
        args.Add(q1.StorageStatus == "S1");//只显示不在库
        args.Add(q1.IsSAP == true);
        args.Add(q1.BoxID == boxId);
        args.Add(q1.IsDeleted == false);

        args.Add(q1.CompanyCode == drpCompany.SelectedValue.Replace(")", "").Split('(')[1]);
        args.Add(q1.CompanyName == drpCompany.SelectedValue.Replace(")", "").Split('(')[0]);

        args.Add(q1.PostingDate >= DateTime.Parse(txtPostingStartDate.Text));
        if (!string.IsNullOrEmpty(txtPostingEndDate.Text))
        {
            args.Add(q1.PostingDate <= DateTime.Parse(txtPostingEndDate.Text + " 23:59:59"));
        }

        if (!string.IsNullOrEmpty(drpDocType.SelectedValue))
        {
            args.Add(q1.VoucherDescription == drpDocType.SelectedValue);
        }
        if (!string.IsNullOrEmpty(txtKey.Text.Trim()))
        {
            argsOr.Add(q1.DocumentsNo.Like("%" + txtKey.Text.Trim() + "%"));
            argsOr.Add(q1.Reference.Like("%" + txtKey.Text.Trim() + "%"));
            argsOr.Add(q1.ReferenceKey.Like("%" + txtKey.Text.Trim() + "%"));
            argsOr.Add(q1.DocumentHeaderText.Like("%" + txtKey.Text.Trim() + "%"));
            args.Add(q1.Or(argsOr.ToArray()));
        }

        if (!string.IsNullOrEmpty(txtKeyStart.Text.Trim()))
        {
            switch (drpKeyType.SelectedValue)
            {
                case "1":
                    argsOr.Add(q1.DocumentsNo >= txtKeyStart.Text.Trim());
                    break;
                case "2":
                    argsOr.Add(q1.Reference >= txtKeyStart.Text.Trim());
                    break;
                case "3":
                    argsOr.Add(q1.ReferenceKey >= txtKeyStart.Text.Trim());
                    break;
                case "4":
                    argsOr.Add(q1.DocumentHeaderText >= txtKeyStart.Text.Trim());
                    break;
            }
            args.Add(q1.Or(argsOr.ToArray()));
        }

        if (!string.IsNullOrEmpty(txtKeyEnd.Text.Trim()))
        {
            switch (drpKeyType.SelectedValue)
            {
                case "1":
                    argsOr.Add(q1.DocumentsNo <= txtKeyEnd.Text.Trim());
                    break;
                case "2":
                    argsOr.Add(q1.Reference <= txtKeyEnd.Text.Trim());
                    break;
                case "3":
                    argsOr.Add(q1.ReferenceKey <= txtKeyEnd.Text.Trim());
                    break;
                case "4":
                    argsOr.Add(q1.DocumentHeaderText <= txtKeyEnd.Text.Trim());
                    break;
            }
            args.Add(q1.Or(argsOr.ToArray()));
        }

        if (!string.IsNullOrEmpty(txtKeyMulti.Text.Trim()))
        {

            switch (drpKeyType.SelectedValue)
            {
                case "1":
                    string[] keys = txtKeyMulti.Text.Trim().Split(new char[] { '\r', '\n' });
                    for (int i = 0; i < keys.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(keys[i]))
                        { argsOr.Add(q1.DocumentsNo == keys[i]); }
                    }
                    break;
                case "2":
                    keys = txtKeyMulti.Text.Trim().Split(new char[] { '\r', '\n' });
                    for (int i = 0; i < keys.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(keys[i]))
                        { argsOr.Add(q1.Reference == keys[i]); }
                    }
                    break;
                case "3":
                    keys = txtKeyMulti.Text.Trim().Split(new char[] { '\r', '\n' });
                    for (int i = 0; i < keys.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(keys[i]))
                        { argsOr.Add(q1.ReferenceKey == keys[i]); }
                    }
                    break;
                case "4":
                    keys = txtKeyMulti.Text.Trim().Split(new char[] { '\r', '\n' });
                    for (int i = 0; i < keys.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(keys[i]))
                        { argsOr.Add(q1.DocumentHeaderText == keys[i]); }
                    }
                    break;
            }
            args.Add(q1.Or(argsOr.ToArray()));
        }


        if (!string.IsNullOrEmpty(drpCompany.SelectedValue))
        {
            args.Add(q1.CompanyName == drpCompany.SelectedValue.Replace(")", "").Split('(')[0]);
            args.Add(q1.CompanyCode == drpCompany.SelectedValue.Replace(")", "").Split('(')[1]);
        }
        if (!string.IsNullOrEmpty(drpFunctionDept.SelectedValue))
        {
            args.Add(q1.FunctionDept == drpFunctionDept.SelectedValue);
        }

        if (!string.IsNullOrEmpty(txtStartDate.Value))
        {
            args.Add(q1.CreatedDttm >= txtStartDate.Value);
        }
        if (!string.IsNullOrEmpty(txtEndate.Value))
        {
            args.Add(q1.CreatedDttm <= DateTime.Parse(txtEndate.Value).AddDays(1));
        }
        if (!string.IsNullOrEmpty(txtUserName.Text.Trim()))
        {
            args.Add(q1.UserName.Like("%" + txtUserName.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtDocumentsType.Text.Trim()))
        {
            args.Add(q1.DocumentsType.Like("%" + txtDocumentsType.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtReferenceTransact.Text.Trim()))
        {
            args.Add(q1.ReferenceTransact.Like("%" + txtReferenceTransact.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtDocumentSystem.Text.Trim()))
        {
            args.Add(q1.DocumentSystem.Like("%" + txtDocumentSystem.Text.Trim() + "%"));
        }
        if (!string.IsNullOrEmpty(txtLogicalSystem.Text.Trim()))
        {
            args.Add(q1.LogicalSystem.Like("%" + txtLogicalSystem.Text.Trim() + "%"));
        }

        q1.Where(args.ToArray()).OrderBy(q1.DocumentsNo.Ascending);
        q1.es.Top = 1000;
        DataTable tableSorce = q1.LoadDataTable();
        pageGrid.DataSource = tableSorce;
        pageGrid.CurrentPage = e.NewPageIndex;
        pageGrid.DataBind();
    }

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);
        Session.Remove("drpDocType");
        Session.Remove("txtKey");
        Session.Remove("drpFunctionDept");
        Session.Remove("sd");
        Session.Remove("ed");
        Session.Remove("txtUserName");
        Session.Remove("txtDocumentsType");
        Session.Remove("txtReferenceTransact");
        Session.Remove("txtDocumentSystem");
        Session.Remove("txtLogicalSystem");
        Session.Remove("drpKeyType");
        Session.Remove("txtKeyMulti");
    }




    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (boxId.HasValue && (!string.IsNullOrEmpty(HiddenFieldIds.Value)))
        {
            string[] idList = HiddenFieldIds.Value.Substring(0, HiddenFieldIds.Value.Length - 1).Split(',');
            using (esTransactionScope tr = new esTransactionScope())
            {
                DateTime now = DateTime.Now;
                string currentUser = LoginUserInfo.CurrentUser.UserName;

                FinBoxReceiptsCollection finBoxReceiptsCollection = new FinBoxReceiptsCollection();
                ArrayList args = new ArrayList();
                ArrayList argsOr = new ArrayList();
                args.Add(finBoxReceiptsCollection.Query.BoxID == boxId);

                for (int i = 0; i < idList.Length; i++)
                {
                    argsOr.Add(finBoxReceiptsCollection.Query.ReceiptID == decimal.Parse(idList[i]));
                    

                    FinReceipt finReceipt = new FinReceipt();
                    finReceipt.LoadByPrimaryKey(decimal.Parse(idList[i]));
                    finReceipt.BoxID = -1;
                    finReceipt.Save();
                }
                if (argsOr.Count > 0)
                { args.Add(finBoxReceiptsCollection.Query.Or(argsOr.ToArray())); }
                finBoxReceiptsCollection.Query.Where(args.ToArray());
                finBoxReceiptsCollection.Query.Load();
                finBoxReceiptsCollection.MarkAllAsDeleted();
                finBoxReceiptsCollection.Save();

                tr.Complete();

                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('已经成功将凭证移出凭证盒！');", true);
            }
        }
    }

    #region  Delete_Command
    protected void Delete_Command(object sender, CommandEventArgs e)
    {
        decimal Id = decimal.Parse(e.CommandArgument.ToString());
        using (esTransactionScope scope = new esTransactionScope())
        {
            FinReceipt finReceipt = new FinReceipt();
            finReceipt.LoadByPrimaryKey(Id);
            finReceipt.BoxID = -1;
            finReceipt.Save();

            FinBoxReceipts finBoxReceipts = new FinBoxReceipts();
            finBoxReceipts.Query.Where(finBoxReceipts.Query.BoxID == boxId, finBoxReceipts.Query.ReceiptID == Id);
            finBoxReceipts.Query.Load();
            finBoxReceipts.MarkAsDeleted();
            finBoxReceipts.Save();

            scope.Complete();
            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "showNews('已经成功将凭证移出凭证盒！');", true);
        }

    }
    #endregion
}